<%@ page language="java" contentType="text/html; charset=UTF-8"
         import="com.baidu.ueditor.ActionEnter"
         import="com.baidu.ueditor.ConfigManager"
         import="cn.cecook.scrm.web.sps.utils.ShiroSessionDataUtil"
         pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%
	String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName()
            + path;
    String cid = ShiroSessionDataUtil.getShiroSessionData().getCid()+"";
%>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>优惠券管理</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link href="<%=path%>/hplus/css/bootstrap.min14ed.css?v=3.3.6" rel="stylesheet">
    <link href="<%=path%>/hplus/css/font-awesome.min93e3.css?v=4.4.0" rel="stylesheet">
    <link href="<%=path%>/hplus/css/plugins/iCheck/custom.css" rel="stylesheet">
    <link href="<%=path%>/hplus/css/plugins/footable/footable.core.css" rel="stylesheet">
    <link href="<%=path%>/hplus/css/animate.min.css" rel="stylesheet">
    <link href="<%=path%>/hplus/css/plugins/clockpicker/clockpicker.css" rel="stylesheet">
    <link href="<%=path%>/hplus/css/plugins/datapicker/datepicker3.css" rel="stylesheet">
	<link rel="stylesheet" type="text/css" href="<%=path%>/hplus/js/plugins/sweetalert/sweetalert2.min.css">
    <link rel="stylesheet" type="text/css" href="<%=path%>/hplus/css/style.min.css"/>
    <link rel="stylesheet" type="text/css" href="<%=path%>/hplus/css/plugins/dataTables/css/jquery.dataTables.min.css"/>
    <style> 
        .col-sm-1{
            font-weight: normal;
        }    
        .caoZuo{font-size: 15px;margin: 0 4px;color:#1ab394} 
        .noclick{font-size: 15px;margin: 0 4px;color:#888}  
    </style>
</head>

<body class="gray-bg">
	<div class="wrapper wrapper-content">
		<div class="tabs-container">
			<ul class="nav nav-tabs">
				<li class="active"><a data-toggle="tab" href="#tab-1"
					aria-expanded="true">电子券管理</a></li>
				<li class=""><a data-toggle="tab" href="#tab-2"
					aria-expanded="false">第三方券管理</a></li>
			</ul>
			<div class="tab-content">
				<div id="tab-1" class="tab-pane active">
					<div class="panel-body">
						<form class="form-horizontal">
							<div class="form-group col-sm-3 text-left" id="data_5">
								<div class="input-daterange input-group" id="datepicker"
									style="padding-left: 15px">
									<input id="start_time" type="text"
										class="input-sm form-control" name="start" readonly value="2017-11-29" style="background-color: white;"/>
									<span class="input-group-addon">到</span> <input id="end_time"
										type="text" class="input-sm form-control" name="end" readonly style="background-color: white;"
										value="2017-12-29" />
								</div>
							</div>
							<div class="col-sm-3">
								<div class="input-group">
									<input id="keyWord" type="text" placeholder="按名称搜索"
										class="input form-control"> <span
										class="input-group-btn">
										<button onclick="javascript:search();" type="button"
											class="btn btn btn-primary">
											<i class="fa fa-search"></i> 搜索
										</button>
									</span>
								</div>
							</div>

							<div class="col-sm-6 form-group">
								<label
									style="line-height: 34px; float: left; margin-right: 5px;">状态</label>
								<select id="select_status" class="form-control" name="account"
									style="width: 100px; float: left;">
									<option value="">全部</option>
									<option value="0">过期</option>
									<option value="1">上架</option>
								</select> <label
									style="line-height: 34px; float: left; margin-right: 5px; margin-left: 5px">种类</label>
								<select id="select_type" class="form-control" name="account"
									style="width: 100px; float: left;">
									<option value="">全部</option>
									<option value="0">代金券</option>
									<option value="1">物品券</option>

								</select> <label
									style="line-height: 34px; float: left; margin-right: 5px; margin-left: 5px">有效期</label>
								<select id="select_useTimeType" class="form-control"
									name="account" style="width: 120px; float: left;">
									<option value="">全部</option>
									<option value="1">相对有效期</option>
									<option value="0">绝对有效期</option>
								</select>
							</div>

							<%--  <div class="col-sm-3 pull-right">
                                <button class="btn btn-primary" type="button" onclick="javascript:window.location.href='<%=path%>/api/bm/ui/createCoupon';">添加</button>
	                            <button class="btn btn-primary" type="button" onclick="javascript:window.location.href='<%=path%>/api/bm/ui/couponReport';">报告</button>
	                            <button class="btn btn-primary" type="button" onclick="javascript:;">标签选项</button>
	                            <button class="btn btn-primary" type="button" onclick="javascript:deletedBatchDialog();">批量删除</button>
                            </div> --%>

						</form>
						<div class="col-md-12" style="padding-left: 0px;">
							<div class="col-md-12 text-right" style="padding-left: 0px;">
								<label class="col-sm-1 control-label" style="padding-top: 17px;padding-left: 0px;">移动端地址：</label>
								<div class="col-md-4" style="padding-top:10px;padding-left:0px;">
									<div class="input-group" style="padding-left:0px;">
										<input type="text" id="urlHref" readonly="readonly" class="form-control" value="">
										<span class="input-group-btn">
                                			<button type="button" class="btn btn-primary" onclick="coypUrl();">复制链接</button>
										</span>
									</div>


								</div>
								<div class="col-md-3" style="text-align: left;padding-top: 19px;">
								<i class="fa fa-question-circle" style="cursor:pointer" data-toggle="tooltip" data-placement="right" title="" data-original-title="会员可通过此地址查看在企业的券列表"></i>
								</div>

								<shiro:hasPermission name="operate_electronic_coupons_manage:create">
								<button type="button" class="btn btn-primary btn-outline"
									onclick="window.location.href='<%=path%>/view/coupon/createCoupon'"
									style="margin-right: 20px">添加</button>
								</shiro:hasPermission>
								<button type="button" class="btn btn-primary btn-outline"
									onclick="window.location.href='<%=path%>/view/coupon/couponReport'"
									style="margin-right: 20px">报告</button>
								<shiro:hasPermission name="operate_electronic_coupons_manage:delete">
								<button onclick="javascript:deletedBatchDialog();"
									class="btn btn-primary btn-outline pull-right" type="button">批量删除</button>
								</shiro:hasPermission>
							</div>
						</div>
						<div class="col-sm-12" style="margin-top: 20px;">
							<div class="ibox float-e-margins">
								<div class="table-responsive">
									<table
										class="display  table-striped table-bordered table-hover"
										id="mydataTable">
										<thead>
											<tr>
												<td>
													<div class="checkbox i-checks">
														<label class="select_all"><input type="checkbox"></label>
													</div> <!-- <input type="checkbox" class="i-checks" name="input[]"> -->
												</td>
												<th>序号</th>
												<th>名称</th>
												<th>种类</th>
												<th class="orderFaceValue">价值</th>
												<th>满减规则</th>
												<th>使用时间</th>
												<th>有效期</th>
												<th class="orderCreateTime">创建日期</th>
												<th>状态</th>
												<th>操作</th>
											</tr>
										</thead>
										<tbody>

										</tbody>
									</table>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div id="tab-2" class="tab-pane">
					<div class="panel-body">
						<form class="form-horizontal">
							<div class="form-group col-sm-3 text-left" id="data_5">
								<div class="input-daterange input-group" id="datepicker"
									style="padding-left: 15px">
									<input id="start_time2" type="text"
										class="input-sm form-control" name="start" readonly style="background-color: white;" value="2017-11-29" />
									<span class="input-group-addon">到</span> <input id="end_time2"
										type="text" readonly class="input-sm form-control" style="background-color: white;" name="end"
										value="2018-12-29" />
								</div>
							</div>
							<div class="col-sm-3">
								<div class="input-group">
									<input id="keyWord2" type="text" placeholder="按名称搜索"
										class="input form-control"> <span
										class="input-group-btn">
										<button onclick="func_dataTableReload2()" type="button"
											class="btn btn btn-primary">
											<i class="fa fa-search"></i> 搜索
										</button>
									</span>
								</div>
							</div>
							<div class="col-sm-6">
								<shiro:hasPermission name="operate_third_party_coupons:create">
							    <button onclick="javascript:func_createModel()" type="button" class="btn btn btn-primary pull-right">新建批次</button>
								</shiro:hasPermission>
							</div>
						</form>

						<div class="col-sm-12" style="margin-top: 20px;">
							<div class="ibox float-e-margins">
								<div class="table-responsive">
									<table
										class="display  table-striped table-bordered table-hover"
										id="thirdPartyCouponTable">
										<thead>
											<tr>
												
												<th>批次名</th>
												<th>创建时间</th>
												<th>导入总量</th>
												<th>状态</th>
												<th>发送渠道</th>
												<th>操作</th>
											</tr>
										</thead>
										<tbody>

										</tbody>
									</table>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<div hidden="" class="modal inmodal fade" id="myModal5" tabindex="-1"
		role="dialog" aria-hidden="true">
		<div class="modal-dialog modal-sm">
			<div class="modal-content">
				<div class="modal-header" style="padding: 15px 15px 10px;">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
					</button>
					<h4 class="text-left">添加优惠券</h4>
				</div>
				<div class="text-center" style="width: 100%; height: 60px;">
					<form method="get" class="form-horizontal col-sm-12"
						style="margin-top: 20px;">
						<div class="form-group">
							<label class="col-sm-3 control-label">券名</label>
							<div class="col-sm-9">
								<input id="coupon_name" type="text" class="form-control"
									maxlength="10" onblur="checkLength(this)">
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-3 control-label">价值</label>
							<div class="col-sm-9">
								<input id="face_value" type="text" class="form-control"
									onkeyup="num(this)" maxlength="7">
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer"
					style="text-align: center; border-top: none;">
					<button type="button" class="btn btn-outline btn-primary"
						data-dismiss="modal">取消</button>
					<button onclick="javascript:createCoupon();" type="button"
						class="btn btn-primary k_verify">保存</button>
				</div>
			</div>
		</div>
	</div>

    <div class="modal inmodal fade" id="couponStatistics" tabindex="-1" role="dialog"  aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
               
            </div>
        </div>
    </div>

    <script src="<%=path%>/hplus/js/jquery.min.js?v=2.1.4"></script>
    <script src="<%=path%>/hplus/js/bootstrap.min.js?v=3.3.6"></script>
    <script src="<%=path%>/hplus/js/content.min.js?v=1.0.0"></script>
    <script src="<%=path%>/hplus/js/plugins/chosen/chosen.jquery.js"></script>
    <script src="<%=path%>/hplus/js/plugins/jsKnob/jquery.knob.js"></script>
    <script src="<%=path%>/hplus/js/plugins/jasny/jasny-bootstrap.min.js"></script>
    <script src="<%=path%>/hplus/js/plugins/datapicker/bootstrap-datepicker.js"></script>
    <script src="<%=path%>/hplus/js/plugins/prettyfile/bootstrap-prettyfile.js"></script>
    <script src="<%=path%>/hplus/js/plugins/switchery/switchery.js"></script>
    <script src="<%=path%>/hplus/js/plugins/ionRangeSlider/ion.rangeSlider.min.js"></script>
    <script src="<%=path%>/hplus/js/plugins/iCheck/icheck.min.js"></script>
    <script src="<%=path%>/hplus/js/plugins/metisMenu/jquery.metisMenu.js"></script>
    <script src="<%=path%>/hplus/js/plugins/colorpicker/bootstrap-colorpicker.min.js"></script>
    <script src="<%=path%>/hplus/js/plugins/clockpicker/clockpicker.js"></script>
    <script src="<%=path%>/hplus/js/plugins/cropper/cropper.min.js"></script>
    <script type="text/javascript" src="<%=path%>/hplus/js/plugins/dataTables/jquery.dataTables.min.js"></script>
    <script src="<%=path%>/hplus/js/demo/form-advanced-demo.min.js"></script>
	<script src="<%=path%>/hplus/js/plugins/suggest/bootstrap-suggest.min.js"></script>
    <script src="<%=path%>/hplus/js/plugins/sweetalert/sweetalert2.min.js"></script>
    <script type="text/javascript" src="<%=path%>/js/marketing/dialog.js"></script>
	<script type="text/javascript" src="<%=path%>/js/marketing/public.js"></script>
	   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
	<script type="text/javascript" src="<%=path%>/js/marketing/lengthlimit.js"></script>
	<script type="text/javascript" src="<%=path%>/js/marketing/validation.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/artDialog/7.0.0/dialog-plus.js"></script>
	<script type="text/javascript" src="<%=path%>/js/dateUtils.js"></script>
	<script type="text/javascript">
        <!-- 页面自加载方法 -->
        $(function(){
            //初始化提示框控件
            $("[data-toggle='tooltip']").tooltip();
            $("#urlHref").val("<%=basePath%>/coupon/ajaxShowWeChatCoupon?cid=<%=cid%>");

        });

    $('.select_all').on('ifChecked', function(event){
    	$(".childCheckbox").attr("checked","checked"); 
		$(".childCheckbox").parent().addClass("checked");
		
		idsList.length=0;
		$('.childCheckbox').each(function(i, d){
			var id=$(this).val();
			
			idsMap.set(id,id);
		})
		idsMap.forEach(function (element, index, array) {
 		    // element: 指向当前元素的值
 		    // index: 指向当前索引
 		    // array: 指向Array对象本身modelIds
 			 idsList.push(element);
 		});
    });
    $('.select_all').on('ifUnchecked', function(event){
    	$(".childCheckbox").removeAttr("checked","checked"); 
		$(".childCheckbox").parent().removeClass("checked");
		
		idsList.length=0;
		$('.childCheckbox').each(function(i, d){
			var id=$(this).val();
			idsMap.delete(id);
		})
		idsMap.forEach(function (element, index, array) {
 		    // element: 指向当前元素的值
 		    // index: 指向当前索引
 		    // array: 指向Array对象本身modelIds
 			 idsList.push(element);
 		});
    });
    
    $(document).on('ifChecked', '.childCheckbox', function() {
    	$(this).attr("checked","checked"); 
		$(this).parent().addClass("checked");
		var id=$(this).val();
		idsList.length=0;
		idsMap.set(id,id);
		idsMap.forEach(function (element, index, array) {
 		    // element: 指向当前元素的值
 		    // index: 指向当前索引
 		    // array: 指向Array对象本身modelIds
 			 idsList.push(element);
 		});
		
		var checkCount=0;
		var totalCoun=0;
		$('.childCheckbox').each(function(i, d){
			totalCoun++;
		})
		$('.checked').each(function(i, d){
			checkCount++;
		})
		if(checkCount==totalCoun){
			$('.select_all').children().addClass("checked");
			$('.select_all').children().children().attr("checked","checked"); 
		}
    });
    $(document).on('ifUnchecked', '.childCheckbox', function() {
    	$(this).removeAttr("checked","checked"); 
		$(this).parent().removeClass("checked");
		var id=$(this).val();
		idsList.length=0;
		idsMap.delete(id);
		idsMap.forEach(function (element, index, array) {
 		    // element: 指向当前元素的值
 		    // index: 指向当前索引
 		    // array: 指向Array对象本身modelIds
 			 idsList.push(element);
 		});
		$('.select_all').children().removeClass("checked"); 
		$('.select_all').children().children().removeAttr("checked"); 
    });
    
    $("#select_status").change(function(){  
    	status=$(this).children('option:selected').val();
    	func_dataTableReload();
    }) 
    $("#select_type").change(function(){  
    	type=$(this).val();
    	func_dataTableReload();
    }) 
    $("#select_useTimeType").change(function(){  
    	validityPeriodType=$(this).children('option:selected').val();
    	func_dataTableReload();
    }) 
    
    
    </script>
    <script>
    $.fn.dataTable.ext.errMode = 'none';
    var path = "<%=path%>";
    var myDataTable;
    var access_token=$.cookie('access_token');
   	var cid=$.cookie('cid');
   	var uid=$.cookie('uid');
   	var keyWord="";
   	var startTime="";
   	var endTime="";
    var name="";
    var face_value="";
    var ids="";
    var status="";
    var type="";
    var validityPeriodType="";
    var orderBy="create_time desc"
    var idsMap=new Map();
    var idsList=new Array();
    var paramJsonObj={};
    var requestModelId=0;
    
    $(function(){
    	init();
    });
    
    function init(){
    	paramJsonObj.cid=cid;
    	paramJsonObj.uid=uid;
    	
    	var myDate = new Date();
    	//获取当前年
    	var year=myDate.getFullYear();
    	//获取当前月
    	var month=myDate.getMonth()+1;
    	var beforeMonth=myDate.getMonth();
    	var beforeYear=year;
    	//获取当前日
    	var day=myDate.getDate(); 
    	if(month>12){
    		year=year+1;
    		month=1;
    	}
    	if(beforeMonth==0){
    		beforeMonth=12;
    		beforeYear=beforeYear-1;
    	}
    	
    	$("#end_time").val(year+"-"+month+"-"+day);
    	$("#end_time").attr("value",year+"-"+month+"-"+day);
    	$("#start_time").attr("value",beforeYear+"-"+beforeMonth+"-"+day);
    	$("#start_time").val(beforeYear+"-"+beforeMonth+"-"+day);
    	
    	$("#start_time").datepicker("setDate",beforeYear+"-"+beforeMonth+"-"+day);
    	$("#end_time").datepicker("setDate",year+"-"+month+"-"+day);  
    	
    	startTime = $("#start_time").val();
       	endTime = $("#end_time").val();
       	
    	myDataTable = dataTable();
    }
    
    function func_dataTableReload(){
    	myDataTable.ajax.reload(function(){
    		$(".i-checks").iCheck({checkboxClass:"icheckbox_square-green",radioClass:"iradio_square-green"});
    		$('input').iCheck('uncheck');
    	});
    }
    
    
    var checkNum=0;
    var totalNum=0;
    function dataTable(){
    	return $('#mydataTable').DataTable({
    		processing: true,
    		ordering: true,
    		searching: false,
    		info: true,
    		autoWidth: true,
    		lengthChange: false,
    		"order": [[ 2, "desc" ]],
    	    language: {
    	    	emptyTable: '没有数据表',
    	    	info: '从第 _START_ 到第 _END_ 条数据；总共有 _TOTAL_ 条记录',
    			infoEmpty: '没有数据',
    			lengthMenu: '每页显示 _MENU_ 条记录',
    			loadingRecords: '正在加载数据....',
    			processing: '正在处理数据....',
    			zeroRecords: '没有找到匹配的记录',
    			paginate: {
    				first: '首页',
    				previous: '前页',
    				next: '后页',
    				last: '尾页'
    			}
    	    },
    	    order: [[8,'desc']],
    		pageLength: 10,
    	    pagingType: 'full_numbers',
    	    columnDefs: [{
       	         'targets' : [0,1,2,3,5,6,7,9,10],    //除第六，第七两列外，都默认不排序
    	         'orderable' : false
                 },{
    			render: function(data, type, full) {
    				if(data=='0'){
    					return "代金券";
    				}else if(data=="1"){
    					return "物品券";
    				}
                },
    			targets: 3
    		},{
    			render: function(data, type, full) {
    				return '<div  title="'+data+'" style="width:80px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;">'+data+'</div>';
                },
    			targets: 2
    		},{
    			render: function(data, type, full) {
    				var result = "无";
    				if(data!=null && data!="" && data!=0){
    					result = Number(data)/100;
    				}
    				return result;
                },
    			targets: 4
    		},{
    			render: function(data, type, row, meta) {
    				var startIndex = meta.settings._iDisplayStart;  
                    return startIndex + meta.row + 1; 
                },
    			targets: 1
    		},{
    			render: function(data, type, full) {
    				var result="";
    				if(data!=null && data!="0"){
    					result="满"+Number(data)/100+"元使用";
    				}else{
    					result="无";
    				}
    				return result;
                },
    			targets: 5
    		},{
    			render: function(data, type, full) {
    				if(full.useTimeType==1){
    					return '<div  title="'+data+" "+full.periodTimeHour+'" style="width:180px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;">'+data+" "+full.periodTimeHour+'</div>';

    				}else{
    					return '无限制';

    				}
				},
    			targets: 6
    		},{
    			render: function(data, type, full) {
    				totalNum++;
    				if(isChecked(data)){
    					checkNum++;
    					return '<div class="checkbox i-checks" style="margin-left:8px;"><label class="is_checkd"><input checked="checked" class="childCheckbox" type="checkbox" value="'+data+'"></label></div>';
    				}else{
    					return '<div class="checkbox i-checks" style="margin-left:8px;"><label class="is_checkd"><input class="childCheckbox" type="checkbox" value="'+data+'"></label></div>';
    				}
    				
                   // return '<div class="checkbox i-checks"><label class="is_checkd"><input class="childCheckbox" type="checkbox" value="'+data+'"></label></div>';
                },
    			targets: 0
    		},{
    			render: function(data, type, full) {
    				var result="";
    				if(data==0){
    					result='<p class="caoZuo" style="color:red">过期</p>';
    				}else{
    					result='<p>上架</p>';
    				}
    			
                    return result;
                },
    			targets: 9
    		},{
    			render: function(data, type, full) {
    				var result = "";
    				<shiro:hasPermission name="operate_electronic_coupons_manage:delete">
    				result += '<a batchId="'+data+'"  class="caozuo edit text-navy" onclick="javascript:deletedDialog(\''+full.id+'\');">删除</a>';
    				</shiro:hasPermission>
    				result += '<a batchId="'+data+'"  class="caozuo delete text-navy" href="<%=path%>/view/coupon/couponSendRecordList?id='+data+'">统计</a>';
                    return result;
                },
    			targets: 10
    		},{
    			render: function(data, type, full) {
    				var result = "";
    				if(data != null){
    					var temp = new Date(full.startTime);
//     					result = temp.getFullYear()+"-"+temp.getMonth()+"-"+temp.getDate()+" "+temp.getHours()+":"+temp.getMinutes()+":"+temp.getSeconds();
						result += temp.getFullYear()+"-"+(temp.getMonth()+1)+"-"+temp.getDate()
						temp = new Date(full.endTime);
    					result += "至"+temp.getFullYear()+"-"+(temp.getMonth()+1)+"-"+temp.getDate();
    				}else if(full.afterDay != null){
    					result = "优惠券发送后"+full.afterDay+"天有效";
    				}
                    return result;
                },
    			targets: 7
    		},{
    			render: function(data, type, full) {
    				var result = "";
    				if(data != null){
    					var temp = new Date(data);
//     					result = temp.getFullYear()+"-"+temp.getMonth()+"-"+temp.getDate()+" "+temp.getHours()+":"+temp.getMinutes()+":"+temp.getSeconds();
    					result = temp.getFullYear()+"-"+(temp.getMonth()+1)+"-"+temp.getDate();
    				}
                    return result;
                },
    			targets: 8
    		}],
    	    columns: func_columns(),
    	    serverSide: true,
    	   
    	    ajax: {
    	    	contentType: 'application/json;charset=utf-8',
    	    	type: 'POST',
    	    	url: func_AjaxUrl(),
    	    	data: function(d){
    	    		d.keyWord=keyWord;
    	    		d.start_time=startTime;
    	    		d.end_time=endTime;
    	    		d.status=status;
    	    		d.type=type;
    	    		d.orderBy=orderBy;
    	    		d.validityPeriodType=validityPeriodType;
    				return JSON.stringify(d);
    			}
    		}
    	    ,
    	    "initComplete": function(settings, json) {
    	    	$(".i-checks").iCheck({checkboxClass:"icheckbox_square-green",radioClass:"iradio_square-green",});
    	      }
    	}).on( 'draw', function () {
    		$(".i-checks").iCheck({checkboxClass:"icheckbox_square-green",radioClass:"iradio_square-green",});
    		if(checkNum==totalNum&&totalNum!=0){
    			$('.select_all').children().addClass("checked");
    			$('.select_all').children().children().attr("checked","checked"); 
    		}else{
    			$('.select_all').children().removeClass("checked"); 
    			$('.select_all').children().children().removeAttr("checked"); 
    		}
    		totalNum=0;
    		checkNum=0;
    	} );
    	
    }
    
    
    
    
    
    function func_AjaxUrl(){
    	return path+"/couponDefinedTemplate/ajaxCouponDefinedTemplatePageList";
    }
    /**
     *	设置列名，对应后台
     */
    function func_columns(){
    	var jsonArr = [
    		{"data":"id"},
    		{"data":"id"},
    		{"data":"name"},
    		{"data":"type"},
    		{"data":"faceValue"},
    		{"data":"limitPrice"},
    		{"data":"periodTimeWeek"},
    		{"data":"endTime"},
    		{"data":"createTime"},
    		{"data":"status"},
    		{"data":"id"},
    	];
    	return jsonArr;
    }
    
    function search(){
    	keyWord=$('#keyWord').val();
    	startTime=$('#start_time').val();
    	endTime=$('#end_time').val();
        func_dataTableReload();
    }

    function onSgelves(id){
    	var url=path+"/couponDefinedTemplate/on_sgelves"
    	$.post(url, {
			"cid" : cid,
			"uid" : uid,
			"access_token" : access_token,
			"id" : id,
		}, function(data) {
			
			if (data.status == 200) {
				func_dataTableReload();
				successDialog("上架成功");
			} else if(data.message=="20028"){
				loginDialog();
			}else {
				errorDialog("上架失败",data.message);
			}
		});
    }
    
    
    //删除一个
    function deleteOne(id){
    	var url=path+"/couponDefinedTemplate/ajaxDeleteTemplateByBatch"
    	$.post(url, {
			"ids" : id,
		}, function(data) {
			
			if (data.status == 200) {
				func_dataTableReload();
				successDialog("删除成功");
			} else if(data.message=="20028"){
				loginDialog();
			}else {
				errorDialog("删除失败",data.message);
			}
		});
    }
    //批量删除
    function deleteBatch(ids){
    		var url=path+"/couponDefinedTemplate/ajaxDeleteTemplateByBatch"
        	$.post(url, {
				"ids" : ids,
			}, function(data) {
				if (data.status == 200) {
					func_dataTableReload();
					successDialog("删除成功");
				} else if(data.message=="20028"){
					loginDialog();
				}else {
					errorDialog("删除失败",data.message);
				}
			});
    	
    }
    
    function offSgelves(id){
    	var url=path+"/couponDefinedTemplate/off_sgelves"
    	$.post(url, {
			"cid" : cid,
			"uid" : uid,
			"access_token" : access_token,
			"id" : id,
		}, function(data) {
			
			if (data.status == 200) {
				func_dataTableReload();
				successDialog("下架成功");
			} else if(data.message=="20028"){
				loginDialog();
			}else {
				errorDialog("下架失败",data.message);
			}
		});
    }
    
    
    function offBatch(ids){
       
    		var url=path+"/couponDefinedTemplate/offSgelvesBatch"
        	$.post(url, {
				"cid" : cid,
				"uid" : uid,
				"access_token" : access_token,
				"ids" : ids,
			}, function(data) {
				
				if (data.status == 200) {
					func_dataTableReload();
					successDialog("下架成功");
				} else if(data.message=="20028"){
					loginDialog();
				}else {
					errorDialog("下架失败",data.message);
				}
			});
    }
    
    function deletedDialog(id){
		swal({
			  title: '您确定要删除此优惠券吗?',
			  text: "删除后将无法恢复，请谨慎操作！",
			  type: 'warning',
			  showCancelButton: true,
			  confirmButtonColor: '#d33',
			  cancelButtonColor: '#3085d6',
			  confirmButtonText: '删除',
			  cancelButtonText:'取消'
			}).then(function () {
				deleteOne(id);
			})
	}
    
    
     function deletedBatchDialog(){
    	 
    	 
    	 var ids="";
     	
     	$(".is_checkd .checked .childCheckbox").each(
 				function(i, d) {
 					ids=ids+","+$(this).val();
 				});
     	ids=ids.replace(",","");
     	if(!StringEmpty(ids)){
     		promptDialog("请选择要删除的优惠券");
     	}else{
     		swal({
  			  title: '您确定要删除选中的优惠券吗?',
  			  text: "删除后将无法恢复，同时用户无法再使用此优惠券进行核销，请谨慎操作！",
  			  type: 'warning',
  			  showCancelButton: true,
  			  confirmButtonColor: '#d33',
  			  cancelButtonColor: '#3085d6',
  			  confirmButtonText: '删除',
  			  cancelButtonText:'取消'
  			}).then(function () {
  				var ids=idsList.join(",");
  				deleteBatch(ids);
  			})
     	} 
    	 
    	
		
	}
    
     
     function offDialog(id){
     	
 		swal({
 			 title: '您确定要下架选中的优惠券吗?',
  			  text: "下架后用户将无法使用此优惠券进行核销，请谨慎操作！",
 			  type: 'warning',
 			  showCancelButton: true,
 			  confirmButtonColor: '#d33',
 			  cancelButtonColor: '#3085d6',
 			  confirmButtonText: '下架',
 			  cancelButtonText:'取消'
 			}).then(function () {
 				offSgelves(id);
 			})
 	}
     
     
      function offBatchDialog(){
    	  var ids="";
      	
      	$(".is_checkd .checked .childCheckbox").each(
  				function(i, d) {
  					ids=ids+","+$(this).val();
  				});
      	ids=ids.replace(",","");
      	if(!StringEmpty(ids)){
      		promptDialog("请选择要下架的优惠券");
      	}else{
      		swal({
   			  title: '您确定要下架选中的优惠券吗?',
   			  text: "下架后用户将无法使用此优惠券进行核销，请谨慎操作！",
   			  type: 'warning',
   			  showCancelButton: true,
   			  confirmButtonColor: '#d33',
   			  cancelButtonColor: '#3085d6',
   			  confirmButtonText: '下架',
   			  cancelButtonText:'取消'
   			}).then(function () {
   				offBatch(ids);
   			})
      	} 
     	 
     	
 		
 	}
      
    //判断是否勾选
      function isChecked(id){
      	var result=false;
      	for(var i in idsList){
      		if(idsList[i]==id){
      			result=true;
      			break;
      		}
      	}
      	return result;
      }
      $('.orderFaceValue').on('click',function(event){
      	var desc=$(this).attr('aria-sort');
      	if(desc=="nudefined"||desc==undefined)
      		orderBy="face_value asc";
      	if(desc=="ascending"){
      		orderBy="face_value desc";
      	}else if(desc=="descending"){
      		orderBy="face_value asc";
      	}
      	
      });
      
      $('.orderCreateTime').on('click',function(event){
      	var desc=$(this).attr('aria-sort');
      	if(desc=="nudefined"||desc==undefined)
      		orderBy="create_time asc";
      	if(desc=="ascending"){
      		orderBy="create_time desc";
      	}else if(desc=="descending"){
      		orderBy="create_time asc";
      	}
      	
      });
        
    </script>
    <script type="text/javascript" src="http://tajs.qq.com/stats?sId=9051096" charset="UTF-8"></script>
    
<script type="text/javascript">
var myDataTable2;

$(function(){
	init2();
});

function init2(){
	myDataTable2 = dataTable2();
}

//新建批次
function func_createModel(){
	var d = dialog({
// 		title: '新建分类',
		content: '批次名：<input id="ThirdPartyCouponModel_name" placeholder="请输入批次名称"/>',
		okValue: "保存",
		ok: function () {
			var name = $('#ThirdPartyCouponModel_name').val();
			name = $.trim(name);
			if(name == ""){
				alert("请输入批次名称");
				return false;
			}
			$.post(path+"/thirdpartyCouponModel/ajaxCreateModel",{name:name},function(data){
				if(data.status == 200){
					successDialog("新建成功");
					func_dataTableReload2(false);
				}else{
					errorDialog("创建失败",data.message);
				}
			},"json");
			this.close();
			this.remove();
		},
		cancel:true,
		cancelValue:"取消"
	});
	d.show();
}

//删除
function func_deleteModel(id){
	swal({
		  title: '您确定要删除此优惠券吗?',
		  text: "删除后将无法恢复，请谨慎操作！",
		  type: 'warning',
		  showCancelButton: true,
		  confirmButtonColor: '#d33',
		  cancelButtonColor: '#3085d6',
		  confirmButtonText: '删除',
		  cancelButtonText:'取消'
		}).then(function () {
			$.post(path+"/thirdpartyCouponModel/ajaxDeleteModel",{id:id},function(data){
				if("200" == data.status){
					successDialog("删除成功");
					func_dataTableReload2(false);
				}else if("601" == data.status){
					errorDialog("删除失败",data.message);
				}else{
					errorDialog("删除失败","内部错误");
				}
			},"json");;
		})
}

//导入
function func_dataImport(modelId){
	paramJsonObj.modelId=modelId+"";
	var paramJsonStr=JSON.stringify(paramJsonObj);
	paramJsonStr=encodeURI(paramJsonStr);
	var downloadTemplate = path+"/excel/couponCode.csv";
	var beanName = "thirdPartyCouponOperator";
	dataImportDialog = dialog({
        width: 400,
        height: 260,
        title: '导入数据',
        url: path + "/bigFileUpload/uploadView?downloadTemplate="+downloadTemplate+"&beanName="+beanName+"&paramJsonStr="+paramJsonStr+"&extensions=csv"
    });
	dataImportDialog.showModal();
}

function func_dataTableReload2(resetPaging) {
	if(resetPaging != undefined){
		myDataTable2.ajax.reload(null,resetPaging);
	}else{
		myDataTable2.ajax.reload();
	}
}

function func_AjaxUrl2() {
    return path + "/thirdpartyCouponModel/ajaxPageList";
}

function func_columns2() {
    var jsonArr = [
    	{"data": "name"},
        {"data": "createTime"},
        {"data": "num"},
        {"data": "status"},
        {"data": "id"},
        {"data": "id"}
    ];
    return jsonArr;
}

function func_ajaxData2() {
    var jsonObject = new Object();
    jsonObject.startTime = $("#start_time2").val()+" 00:00:00";
    jsonObject.endTime = $("#end_time2").val()+" 23:59:59";
    var name = $.trim($("#keyWord2").val());
    if(name != ""){
    	jsonObject.nameLike = name;
    }
    return jsonObject;
}

function dataTable2() {
    return $('#thirdPartyCouponTable').DataTable({
        processing: true,
        ordering: false,
        searching: false,
        info: true,
        autoWidth: false,
        lengthChange: false,
        language: {
            emptyTable: '没有数据表',
            info: '从第 _START_ 到第 _END_ 条数据；总共有 _TOTAL_ 条记录',
            infoEmpty: '没有数据',
            lengthMenu: '每页显示 _MENU_ 条记录',
            loadingRecords: '正在加载数据....',
            processing: '正在处理数据....',
            zeroRecords: '没有找到匹配的记录',
            paginate: {
                first: '首页',
                previous: '前页',
                next: '后页',
                last: '尾页'
            }
        },
        order: [[1, 'desc']],
        pageLength: 10,
        pagingType: 'full_numbers',
        columnDefs: [{
            render: function (data, type, full) {
            	var requestUrl="<%=path%>/view/coupon/thirdPartyCouponStatistics?modelId="+data;
                var result = "";
                <shiro:hasPermission name="operate_third_party_coupons:import">
                result += "<a href='javascript:void(0)' onclick='javascript:func_dataImport(\""+data+"\")' style='color:#1ab394'>导入</a>&nbsp;";
                </shiro:hasPermission>
                if(full.status==0){
                	 result += "<a id='"+data+"' style='color:#999999' disabled='true'>统计</a>&nbsp;";
                }else{
                	 result += "<a id='"+data+"' style='color:#1ab394' data-toggle='modal' href='"+requestUrl+"' data-target='#couponStatistics'>统计</a>&nbsp;";
                }
                <shiro:hasPermission name="operate_third_party_coupons:delete">
                result += "<a href='javascript:void(0)' onclick='func_deleteModel(\""+data+"\")' style='color:#1ab394'>删除</a>";
                </shiro:hasPermission>
                return result;
            },
            targets: 5
		},{
			render: function(data, type, full) {
				var result="";
				if(data == "1"){
					result="未派送";
				}else if(data=="2"){
					result="派送中";
				}else if(data=="3"){
					result="派送完毕";
				}else {
					result="未导入";
				}
				return result;
            },
			targets: 3
		},{
			render: function(data, type, full) {
				var result="";
				if(data != null){
					$.ajax({
						async: false,
						url: path+"/thirdpartyCoupon/ajaxThirdpartyCouponStatisticsDetail?modelId="+data,
						success: function(data){
							if(data.status == "200"){
								$.each(data.data,function(i,d){
									result += "<p>"+d.channelName+"："+d.name+"</p>";
								});
							}
						}
					});
				}
				return result;
            },
			targets: 4
		},{
			render: function(data, type, full) {
				return formatDateTimeYMDHMS(data);
            },
			targets: 1
		}],
        columns: func_columns2(),
        serverSide: true,
        ajax: {
            contentType: 'application/json;charset=utf-8',
            type: 'POST',
            url: func_AjaxUrl2(),
            data: function (d) {
            	d.extra_search = func_ajaxData2();
				return JSON.stringify(d);
            }
        }
	});
    
    function setRequestModelId(modelId){
    	requestModelId=modelId;
    }
    
}

//复制网址
function coypUrl(){
    var val=document.getElementById("urlHref");
    val.select(); // 选择对象
    document.execCommand("Copy"); // 执行浏览器复制命令
}

</script>
</body>
</html>
